<script setup>
import { User, Lock, Discount } from '@element-plus/icons-vue'
import { ref, reactive } from 'vue'
import { ElMessage, ElNotification } from 'element-plus'
//使用路由，导出useRouter函数
import { useRouter } from 'vue-router';
const router = useRouter()

import { useTokenStore } from '@/stores/token.js'
const tokenstore = useTokenStore();

//调用后台接口，完成注册
import { userRegisterService, userLoginService, getallmajorsService } from '@/api/user.js'

//控制注册与登录表单的显示， 默认显示注册
const isRegister = ref(false)
const allmajors = ref(['销售员工', '片区负责人', '部门负责人', '领导', '超级管理员'])
//定义注册和登录的数据模型
const registerData = ref({
    account: '',
    pass: '',
    type: ''
})
const formref = ref(null); //表单校验
const registerStudentUser = ref({
    name: null,
    age: null,
    majorName: null,
    phoneNumber: null,
    enrollmentTime: null,
})

//用于注册的表单校验模型
const rules = {
    account: [
        { required: true, message: '请输入账号', trigger: 'blur' },
    ],
    pass: [
        { required: true, message: '请输入密码', trigger: 'blur' },
    ],
    type: [
        { required: true, message: '请选择角色类型', trigger: 'blur' },
    ],
}


const register = async () => {
    console.log(registerStudentUser.value);
    let result = await userRegisterService(registerStudentUser.value);
    console.log(result);
    if (result.code == 0) {
        ElMessage.success('注册成功')
        registerData.value.userName = result.data;
        registerStudentUser.value.name = null;
        registerStudentUser.value.age = null;
        registerStudentUser.value.enrollmentTime = null;
        registerStudentUser.value.phoneNumber = null;
        registerStudentUser.value.majorName = null;
        isRegister.value = false
        open();
    }
    else {
        ElMessage.error(result.message ? result.message : '注册失败')
    }
}
const cleardata = () => {
    registerStudentUser.value.name = null;
    registerStudentUser.value.age = null;
    registerStudentUser.value.enrollmentTime = null;
    registerStudentUser.value.phoneNumber = null;
    registerStudentUser.value.majorName = null;
    isRegister.value = true;
}
const login = async () => {
    formref.value.validate(async (valid) => {
        if (!valid) {
            ElMessage.error('信息填写不完整！');
        }
        else {
            let result = await userLoginService(registerData.value);
            console.log(result);

            if (result.code == 0) {
                ElMessage.success('登录成功')
                //把得到的token存储到pinia中
                console.log(result.data);
                tokenstore.setToken(result.data)
                console.log(tokenstore.token);
                router.push('/') //跳转页面
            }
            else {
                //失败
                ElMessage.error(result.message ? result.message : '登录失败');
            }
        }
    });
}
const open = () => {
    ElNotification.success({
        title: 'Success', message: '请牢记您的学号/账号：' + registerData.value.userName + '\n您的初始密码：123456',
        offset: 25, duration: 0
    })
}
</script>

<template>

    <el-row class="login-page">
        <el-col :span="17" class="bg"></el-col>
        <el-col :span="5" :offset="1" class="form">
            <!-- 注册表单 -->
            <el-form ref="form" size="large" autocomplete="off" v-if="isRegister" :model="registerStudentUser"
                :rules="registerDataRules" label-width="80px">
                <el-form-item>
                    <h1>注册</h1>
                </el-form-item>
                <el-form-item label="姓名" prop="name">
                    <el-input placeholder="请输入姓名" v-model="registerStudentUser.name"></el-input>
                </el-form-item>
                <el-form-item label="年龄" prop="age">
                    <el-input type="number" placeholder="请输入年龄" v-model="registerStudentUser.age"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phoneNumber">
                    <el-input type="number" placeholder="请输入手机号" v-model="registerStudentUser.phoneNumber"></el-input>
                </el-form-item>
                <el-form-item label="入学时间" prop="enrollmentTime">
                    <el-date-picker v-model="registerStudentUser.enrollmentTime" type="datetime" placeholder="选择入学时间"
                        style="width: 300px">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="专业" prop="majorName">
                    <el-select placeholder="请选择专业" clearable style="width: 300px"
                        v-model="registerStudentUser.majorName">
                        <el-option v-for="c in allmajors" :key="c" :label="c" :value="c">
                        </el-option>
                    </el-select>
                </el-form-item>
                <!-- 注册按钮 -->
                <!-- <el-form-item>
                    <el-button class="button" type="primary" auto-insert-space @click="register">
                        注册
                    </el-button>
                </el-form-item>
                <el-form-item class="flex">
                    <el-link type="info" :underline="false" @click="isRegister = false">
                        ← 返回
                    </el-link>
                </el-form-item> -->
            </el-form>
            <!-- 登录表单 -->
            <el-form ref="formref" autocomplete="off" :rules="rules" :model="registerData" size="large">
                <el-form-item>
                    <h1>Java作业4~<br>营销服务一体化管理系统</h1>
                </el-form-item>
                <el-form-item prop="account">
                    <el-input :prefix-icon="User" placeholder="请输入账号" v-model="registerData.account"
                        clearable></el-input>
                </el-form-item>
                <el-form-item prop="pass">
                    <el-input show-password :prefix-icon="Lock" type="password" placeholder="请输入密码"
                        v-model="registerData.pass" clearable></el-input>
                </el-form-item>
                <el-form-item prop="type">
                    <el-select placeholder="请选择角色" clearable style="width: 350px" v-model="registerData.type">
                        <template #prefix>
                            <el-icon>
                                <Discount />
                            </el-icon>
                        </template>
                        <el-option v-for="c in allmajors" :key="c" :label="c" :value="c">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item class="flex">
                    <div class="flex">
                        <el-checkbox>记住我</el-checkbox>
                        <el-link type="primary" :underline="false">忘记密码？</el-link>
                    </div>
                </el-form-item>

                <!-- 登录按钮 -->
                <el-form-item>
                    <el-button class="button" type="primary" auto-insert-space @click="login">登录</el-button>
                </el-form-item>
                <!-- <el-form-item class="flex">
                    <el-link type="info" :underline="false" @click="cleardata">
                        注册 →
                    </el-link>
                </el-form-item> -->
            </el-form>
        </el-col>
    </el-row>
</template>
<style lang="scss" scoped>
/* 样式 */
.login-page {
    height: 100vh;
    background-color: #fff;

    .bg {
        background: url('@/assets/login_bg.jpg') no-repeat center / cover;
        border-radius: 0 20px 20px 0;
    }

    .form {
        display: flex;
        flex-direction: column;
        justify-content: center;
        user-select: none;

        .title {
            margin: 0 auto;
        }

        .button {
            width: 100%;
        }

        .flex {
            width: 100%;
            display: flex;
            justify-content: space-between;
        }
    }
}
</style>